// import EventBus from "./eventBus.js"
import {
  _type
} from "../utils/index.js"
// dom操作



// 事件
export const _events = (el, events) => {
  if (events) {
    let type = _type(events)
    switch (type) {
      case 'function':
        el.addEventListener('click', events)
        break;
      case 'object':
        Object.keys(events).forEach(key => {
          let fn = (e) => {
            events[key](e, {
              model: e.detail //自定义
            })
          }
          el.addEventListener(key, fn)
        })
        break
    }
  }
  return el
}

// 样式
export const _style = (el, options = {}) => {
  el.style = Object.keys(options).map(t => {
    return `${t}:${options[t]}`
  }).join(";")
}

// 属性
export const _attr = (el, key, val) => {
  if (val === undefined) {
    return el.getAttribute(key)
  } else {
    if (val != null) {
      el.setAttribute(key, val)
    }
  }
}

export const _children = (el, children) => {
  if (Array.isArray(children)) {
    children.forEach(t => _children(el, t))
  } else {
    children && el.appendChild(children)
  }
}

export const createElement = (tag, options = {}, events, children) => {
  let el = document.createElement(tag)
  const addContent = (val) => {
    if (options.isHtml) {
      el.innerHTML += val
    } else {
      el.textContent += val
    }
  }

  // 子节点
  const _children = (val) => {
    let type = _type(val)
    switch (type) {
      case 'string':
        addContent(val)
        break;
      case 'number':
        addContent(String(val))
        break;
      case 'object':
        addContent(JSON.stringify(val))
        break;
      case 'array':
        val.forEach(t => _children(t))
        break;
      default:
        el.appendChild(val)
    }
  }



  // 属性 样式
  const _props = (key, val) => {
    switch (key) {
      case 'children':
        _children(val)
        break;
      case 'text': case 'label':
        addContent(val)
        break;
      case 'width':
        _attr(el, key, val)
        break;
      case 'style':
        _style(el, val)
        break;
      case 'disabled':
        if (val) {
          _attr(el, key, val)
        }
        break
      default:
        let type = _type(val)
        if (!['array', 'object'].includes(type)) {
          _attr(el, key, val)
        }
    }
  }
  // 属性
  if (options) {
    Object.keys(options).forEach(key => {
      let val = options[key]
      // if (tag === 'input' && key === 'checked' && !val) {
      //   // 不设置
      // } else {
        
      // }
      _props(key, val)

    })
  }

  // 事件
  if (events) {
    _events(el, events)
  }
  //子节点
  if (children) {
    _children(children)
  }
  return el
}

export const _c = (tag, options, events, children) => {
  return createElement(tag, options, events, children)
}

// css转属性
// .a.b   .a[b=c] #a
export const toProp = (selector) => {
  let first = selector.slice(0, 1)
  let prop = selector.slice(1)
  if ('#' === first) {
    return {
      id: prop
    }
  } else if ('.' === first) {
    let reg = /(.*?)\[(.*?)=(.*?)\]/
    if (reg.test(prop)) {
      let arr = prop.match(reg)
      return {
        class: arr[1],
        [arr[2]]: arr[3]
      }
    }
    return {
      class: prop.split(".").join(" ")
    }
  }
}

// 插入节点
export const _append = (el, children) => {

  if (_type(el) === 'string') {
    let target = el
    let $el = _query(el)
    if (!$el) {
      $el = dom.div("", {
        ...toProp(target)
      })
      document.body.appendChild($el)
    }
    el = $el
  }

  if (_type(children) === "string") {
    el.appendChild(_textNode(children))
  } else if (Array.isArray(children)) {
    children.forEach(t => _append(el, t))
  } else {
    children && el.appendChild(children)
  }


  return el
}


export const _div = (children, options, events) => {
  return _c("div", children, options, events)
}

export const _textNode = (text) => {
  return document.createTextNode(text)
}


// 移除
export const _remove = (el, index) => {
  let children = el.childNodes
  if (children && children.length) {
    switch (index) {
      case 'last':
        el.removeChild(children[children.length - 1]);
        break;
      case "frist":
        el.removeChild(children[0]);
        break
      default:
        if (_type(index) === 'number') {
          el.removeChild(children[index]);
        }
    }
  }
  return el
}

// 查找
export const _query = (condition, el) => {
  if (condition) {
    if (el) {
      return el.querySelector(condition)
    } else {
      return document.querySelector(condition)
    }
  }
}

export const _queryAll = (condition, el) => {
  let nodelist = []
  if (condition) {
    if (el) {
      nodelist = el.querySelectorAll(condition)
    } else {
      nodelist = document.querySelectorAll(condition)
    }

  }

  return Array.from(nodelist)
}

// 清空子节点
export const _empty = (el) => {
  // let len = el.childNodes.length
  // for (let i = 0; i < len; i++) {
  //   el.removeChild(el.childNodes[0])
  // }
  while (el.hasChildNodes()) {
    //当el下还存在子节点时 循环继续
    el.removeChild(el.firstChild)
  }
  return el
}




export const _closest = (el, cls) => {
  // if(cls[0]==='.')
  if (/\.\S*?/.test(cls)) {
    if (el.classList && el.classList.contains(cls.slice(1))) {
      return el
    } else if (el.parentNode) {
      return _closest(el.parentNode, cls)
    } else {
      return undefined
    }
  } else if (_type(cls) === 'string') {
    if (el.nodeName && el.nodeName.toLowerCase() === cls.toLowerCase()) {
      return el
    } else if (el.parentNode) {
      return _closest(el.parentNode, cls)
    } else {
      return undefined
    }
  }
}

const dom = {};
['form', 'select', 'option', 'input', 'button', 'div', 'span',
  'font', 'i', 'label', 'tr', 'thead', 'tbody', 'tfoot', 'table',
  'td', 'th', 'ul', 'li'].forEach(t => {
    dom[`${t}`] = (children, options, events) => _c(t, options, events, children)
  });

export { dom }

export const _toggleClassName = (el, cls) => {
  if (!el) return
  if (el.classList.contains(cls)) {
    el.classList.remove(cls)
  } else {
    el.classList.add(cls)
  }
}

export const _removeClassName = (el, cls) => {
  if (!el) return
  if (Array.isArray(el)) {
    el.forEach(t => _removeClassName(t, cls))
  } else {
    el.classList.remove(cls)
  }

}

export const _addClassName = (el, cls) => {
  if (!el) return
  if (Array.isArray(el)) {
    el.forEach(t => _addClassName(t, cls))
  } else {
    el.classList.add(cls)
  }

}

// 根据css选择器 创建节点
// .a .b
export const _layout = (selector, root = document.body) => {
  let arr = selector.split(" ")
  let first = arr.shift()
  let last = arr.join(" ")
  let el = _query(first, root)
  if (!el && first) {
    el = dom.div("", {
      ...toProp(first)
    })
    _append(root, el)
  }
  if (last && el) {
    _layout(last, el)
  }
  return _query(selector, root)
}


// 手风琴
export const _accordion = (panel, current, target, root) => {
  // let brothers = _queryAll(current.replace(/=.*?\]/, "]"), root) //'.panel[role]'
  // brothers.forEach(t => _addClassName(t, "hide"))
  let el = _query(current) //`.panel[role=${t.name}]`
  if (el) {
    el.parentNode.childNodes.forEach(t => _addClassName(t, "hide"))
    _removeClassName(el, "hide")
  } else {
    let container = target ? _layout(target, root) : root
    container.childNodes.forEach(t => _addClassName(t, "hide"))
    _append(container, panel)
  }
}

let toggleStyleFlag = true
export const _toggleStyle = (el, cssA, cssB) => {
  if (toggleStyleFlag) {
    _style(el, cssA)
    toggleStyleFlag = false
  } else {
    _style(el, cssB)
    toggleStyleFlag = true
  }
  return toggleStyleFlag
}
